package ore.example.pokemoninfo.utils;

import com.pixelmonmod.pixelmon.api.pokemon.Pokemon;
import com.pixelmonmod.pixelmon.api.pokemon.PokemonFactory;
import com.pixelmonmod.pixelmon.api.pokemon.stats.BattleStatsType;
import com.pixelmonmod.pixelmon.api.storage.PartyStorage;
import com.pixelmonmod.pixelmon.api.storage.PlayerPartyStorage;
import com.pixelmonmod.pixelmon.api.storage.StorageProxy;
import com.pixelmonmod.pixelmon.api.util.helpers.SpriteItemHelper;
import de.tr7zw.nbtapi.NBTItem;
import net.minecraft.core.RegistryAccess;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.TagParser;
import org.bukkit.Bukkit;
import org.bukkit.craftbukkit.v1_21_R1.CraftServer;
import org.bukkit.craftbukkit.v1_21_R1.inventory.CraftItemStack;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import java.util.ArrayList;
import java.util.List;

public class ConvertPokemon {

    /**
     * 将宝可梦转换为可携带的相片物品，并写入完整 NBT 数据。
     *
     * @param player       玩家
     * @param pokemonIndex 队伍中的宝可梦索引 (0-5)
     */
    public static void convertPokemonToItem(Player player, int pokemonIndex) {
        try {
            RegistryAccess registryAccess = ((CraftServer) Bukkit.getServer()).getServer().registryAccess();
            PartyStorage storage = StorageProxy.getPartyNow(player.getUniqueId());
            if (storage == null) {
                player.sendMessage("§c未找到你的队伍数据！");
                return;
            }

            Pokemon pokemon = storage.get(pokemonIndex);
            if (pokemon == null) {
                player.sendMessage("§c该槽位没有宝可梦！");
                return;
            }

            // === 判断是否锁定（神兽或3V以上） ===
            int perfectIVCount = 0;
            if (pokemon.getIVs().getStat(BattleStatsType.HP) == 31) perfectIVCount++;
            if (pokemon.getIVs().getStat(BattleStatsType.ATTACK) == 31) perfectIVCount++;
            if (pokemon.getIVs().getStat(BattleStatsType.DEFENSE) == 31) perfectIVCount++;
            if (pokemon.getIVs().getStat(BattleStatsType.SPECIAL_ATTACK) == 31) perfectIVCount++;
            if (pokemon.getIVs().getStat(BattleStatsType.SPECIAL_DEFENSE) == 31) perfectIVCount++;
            if (pokemon.getIVs().getStat(BattleStatsType.SPEED) == 31) perfectIVCount++;

            boolean is3V = perfectIVCount >= 3;
            boolean isLegendary = pokemon.isLegendary();
            boolean isLocked = isLegendary || is3V;

            // === 创建照片物品 ===
            net.minecraft.world.item.ItemStack nmsStack = SpriteItemHelper.getPhoto(pokemon);
            ItemStack bukkitItem = CraftItemStack.asBukkitCopy(nmsStack);

            // === 设置展示信息 ===
            ItemMeta meta = bukkitItem.getItemMeta();
            if (meta != null) {
                String display = (pokemon.isShiny() ? "§e✦ " : "§b") + pokemon.getTranslatedName().getString();

                List<String> lore = new ArrayList<>();
                lore.add("§7等级: §f" + pokemon.getPokemonLevel());

                if (isLocked) {
                    lore.add("§8§m---------------");
                    String ownerName = Bukkit.getOfflinePlayer(player.getUniqueId()).getName(); // 获取玩家名字
                    lore.add("§c⚠ 已锁定(需要由 " + ownerName + " 解锁)");
                    lore.add("§8§m---------------");
                }

                meta.setDisplayName(display);
                meta.setLore(lore);
                bukkitItem.setItemMeta(meta);
            }

            // === 写入完整 NBT 数据 ===
            NBTItem nbti = new NBTItem(bukkitItem);
            CompoundTag pokemonTag = new CompoundTag();
            pokemon.writeToNBT(pokemonTag, registryAccess);
            String serialized = pokemonTag.toString();

            nbti.setString("pokemon_data", serialized);
            nbti.setString("pokemon_name", pokemon.getTranslatedName().getString());
            nbti.setInteger("pokemon_level", pokemon.getPokemonLevel());
            nbti.setBoolean("is_shiny", pokemon.isShiny());
            nbti.setInteger("party_index", pokemonIndex);
            nbti.setString("owner_uuid", player.getUniqueId().toString());
            nbti.setBoolean("pokemon_locked", isLocked);

            bukkitItem = nbti.getItem();

            // === 给玩家物品并从队伍移除 ===
            player.getInventory().addItem(bukkitItem);
            player.sendMessage("§a成功将宝可梦 §e[" + pokemon.getTranslatedName().getString() + "] §a转换成相片！");
            storage.set(pokemonIndex, null);
        } catch (Exception e) {
            player.sendMessage("§c拍照过程中出现错误，请联系管理员！");
            e.printStackTrace();
        }
    }

    /**
     * 从相片物品还原出宝可梦。
     */
    public static void restorePokemonFromItem(Player player, ItemStack item) {
        NBTItem nbti = new NBTItem(item);
        if (!nbti.hasKey("pokemon_data")) {
            player.sendMessage("§c该物品没有宝可梦数据！");
            return;
        }



        String pokemonData = nbti.getString("pokemon_data");
        try {
            CompoundTag parsedTag = TagParser.parseTag(pokemonData);
            RegistryAccess registryAccess = ((CraftServer) Bukkit.getServer()).getServer().registryAccess();

            Pokemon pokemon = PokemonFactory.create(parsedTag, registryAccess);
            PlayerPartyStorage storage = StorageProxy.getPartyNow(player.getUniqueId());
            if (storage == null) {
                player.sendMessage("§c无法找到你的队伍数据！");
                return;
            }

            boolean added = storage.add(pokemon);
            if (!added) {
                player.sendMessage("§c你的队伍已满，无法添加宝可梦！");
                return;
            }

            item.setAmount(item.getAmount() - 1);
            player.sendMessage("§a成功还原宝可梦 §e" + pokemon.getTranslatedName().getString() + "§a！");
        } catch (Exception e) {
            e.printStackTrace();
            player.sendMessage("§c宝可梦还原失败，请联系管理员！");
        }
    }
}
